/* @(#)config.c
 * Time-stamp: <2008-10-08 21:12:34 root>
 * Copyright 2008 Julian Qian
 * Author: root@localhost.localdomain
 * Version: $Id: config.c,v 0.0 2008/09/27 16:51:04 root Exp $
 * Keywords: 
 */

#include "common.h"

/* return: value */
int get_config(char *filepath, char *cate, char *name, char *value){
	FILE *fp;
	int flag = 0;
	char buf[MAXLEN], cate1[MAXLEN], name1[MAXLEN];
	char *ptr;
	if( (fp = fopen(filepath, "r")) == NULL){
		return -1;
	}
	sprintf(cate1, "[%s]", cate);
	sprintf(name1, "%s=", name);

	while(feof(fp) == 0){
		memset(buf, 0, sizeof(buf));
		fgets(buf, sizeof(buf), fp); /* read each line */
		if(buf[0] == '#'){
			continue; /* comment */
		}else if(flag == 0 && buf[0] == '['){ /* match */
			if(strncmp(buf, cate1, strlen(cate1)) == 0) flag = 1;
		}else if(flag == 1 && buf[0] == '['){
			break; /* end */
		}else{
			if(strncmp(buf, name1, strlen(name1)) == 0){
				ptr = buf+strlen(name1);
				ptr = trim(ptr);
				strncpy(value,ptr,strlen(ptr));

				/* ASSERT(get_config_val_sub(buf, value, type) == 0); */
				fclose(fp);
				return 0;
			}
		}
	}
	fclose(fp);
	return -1;
}

int get_db_config(char *filepath, DB_CONN *dbc){
	memset(dbc, 0, sizeof(DB_CONN));
	return get_config(filepath, "DATABASE", "HOSTNAME", dbc->hostname) |
		get_config(filepath, "DATABASE", "USERNAME", dbc->username) |
		get_config(filepath, "DATABASE", "PASSWORD", dbc->password) |
		get_config(filepath, "DATABASE", "DATABASE", dbc->database);
}
